package com.tools.web.email;

import com.tools.common.object.Note;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;

import java.util.Arrays;

/**
 * 自定义的邮件夹对象
 * */
@Note("自定义的邮件夹对象")
public final class MailFolder {

    @Note("邮件总数")
    private final int messageCount;

    @Note("未读邮件总数")
    private final int unreadMessageCount;

    @Note("新邮件总数")
    private final int newMessageCount;

    @Note("已删除的邮件总数")
    private final int deletedMessageCount;

    @Note("自定义的邮件实例数组，搜索的数组都在这")
    private final MailEntity[] messages;

    /* **********************************************************************************
     *
     *          构造器
     *
     * *********************************************************************************
     * */

    public MailFolder(Folder folder) {
        this(folder, new FlagTerm(new Flags(Flags.Flag.SEEN), false));
    }


    public MailFolder(Folder folder, SearchTerm searchTerm) {
        MailKit.openFolder(folder, Folder.READ_WRITE);
        this.messageCount = MailKit.getMessageCount(folder);
        this.unreadMessageCount = MailKit.getUnreadMessageCount(folder);
        this.newMessageCount = MailKit.getNewMessageCount(folder);
        this.deletedMessageCount = MailKit.getDeletedMessageCount(folder);
        Message[] unreadMessages = (searchTerm == null)
                ? MailKit.getAllMessages(folder)
                : MailKit.searchMessages(folder, searchTerm);
        int length = unreadMessages.length;
        this.messages = new MailEntity[length];
        for (int i = 0; i < length; i++) {
            this.messages[i] = new MailEntity(unreadMessages[i]);
        }
        MailKit.close(folder);
    }

    /* **********************************************************************************
     *
     *          Getter
     *
     * *********************************************************************************
     * */

    public int getMessageCount() {
        return messageCount;
    }

    public int getUnreadMessageCount() {
        return unreadMessageCount;
    }

    public int getNewMessageCount() {
        return newMessageCount;
    }

    public int getDeletedMessageCount() {
        return deletedMessageCount;
    }

    public MailEntity[] getMessages() {
        return messages;
    }

    @Override
    public String toString() {
        return "MailFolder{" +
                "messageCount=" + messageCount +
                ", unreadMessageCount=" + unreadMessageCount +
                ", newMessageCount=" + newMessageCount +
                ", deletedMessageCount=" + deletedMessageCount +
                ", messages=" + Arrays.toString(messages) +
                '}';
    }
}
